package com.commonlib.downloadmgr.subclass;

import java.io.File;

import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.commonlib.downloadmgr.R;
import com.commonlib.downloadmgr.base.DownloadBaseAdapter;
import com.commonlib.downloadmgr.base.DownloadBaseHelper;
import com.commonlib.downloadmgr.base.DownloadBaseJob;
import com.commonlib.downloadmgr.base.DownloadBaseManager;
import com.commonlib.downloadmgr.entity.Entity;
import com.commonlib.downloadmgr.util.Utility;

public class DownloadAdapter extends DownloadBaseAdapter<Entity>{
	private static final String TAG = DownloadAdapter.class.getSimpleName();
	public static final String PREFIX_PROGRESSBAR = "prefix_progressbar_";
	public static final String PREFIX_PERCENTAGE = "prefix_percentage_";
	public static final String PREFIX_SWITCH = "prefix_switch_";
	public static final String PREFIX_CONVERTVIEW = "prefix_convertview";
	
	public static final int INDEX_HOLDER = 0;
	public static final int INDEX_ID = 1;
	private Context context;
	public DownloadAdapter(Context context) {
		this.context = context;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder;
		int maxIndex = getCount() - 1;
		position = maxIndex - position;
		checkLocalFile(getItem(position));
		if (convertView == null) {
			convertView = LayoutInflater.from(context).inflate(R.layout.download_item, null);
			holder = new ViewHolder();
			holder.tvTitle = (TextView)convertView.findViewById(R.id.download_item_tv_title);
			holder.tvSize = (TextView)convertView.findViewById(R.id.download_item_tv_size);
			holder.tvPercentage = (TextView)convertView.findViewById(R.id.download_item_tv_percent);
			holder.ivIcon = (ImageView)convertView.findViewById(R.id.download_item_iv_icon);
			holder.pbDownloading = (ProgressBar)convertView.findViewById(R.id.download_item_pb);
			holder.bnSwitch = (Button)convertView.findViewById(R.id.download_item_bt_switch);
			holder.bnCancel = (Button)convertView.findViewById(R.id.download_item_bt_cancel);
			holder.ckbSelect = (CheckBox)convertView.findViewById(R.id.download_item_ckb);
			convertView.setTag(R.id.tag_id_convert_holder, holder);
		}else{
			holder = (ViewHolder) convertView.getTag(R.id.tag_id_convert_holder);
		}
		holder.tvTitle.setText(getItem(position).getEntity().title);
		holder.tvSize.setText(DownloadBaseHelper.formatSizeUnit(getItem(position).getmTotalSize()));
		int state = getItem(position).getState();
		switch (state) {
		case DownloadBaseJob.STATE_IDLE:
			holder.bnSwitch.setVisibility(View.INVISIBLE);
			holder.pbDownloading.setIndeterminate(true);
			holder.tvPercentage.setVisibility(View.INVISIBLE);
			break;
		case DownloadBaseJob.STATE_DOWNLOADING:
		case DownloadBaseJob.STATE_PAUSED:
		case DownloadBaseJob.STATE_SUCCESS:
		case DownloadBaseJob.STATE_FAILED:
			holder.bnSwitch.setVisibility(View.VISIBLE);
			holder.bnSwitch.setText(getSwitchString(context, getItem(position)));
			
			holder.tvPercentage.setVisibility(View.VISIBLE);
			int iProgress = getItem(position).getmProgress();
			holder.pbDownloading.setIndeterminate(false);
			holder.pbDownloading.setMax(100);
			holder.pbDownloading.setProgress(iProgress);
			if (state == DownloadBaseJob.STATE_FAILED) {
				holder.tvPercentage.setTextColor(Color.RED);
				holder.tvPercentage.setText(getErrorMsg(getItem(position).getErrorCode()));
			}else{
				holder.tvPercentage.setTextColor(Color.WHITE);
				holder.tvPercentage.setText(iProgress + "%");
			}
			break;
		default:
			Log.e(TAG, "wrong state " + state);
			break;
		}
		holder.bnSwitch.setTag(position);
		holder.bnCancel.setTag(position);
		holder.bnSwitch.setOnClickListener(onSwitchClickListener);
		holder.bnCancel.setOnClickListener(onCalcelClickListener);
		
		convertView.setTag(PREFIX_CONVERTVIEW + getItem(position).getId());
		return convertView;
	}

	@Override
	public DownloadBaseManager<Entity> getDownloadManager() {
		return DownloadManager.getInstance(context);
	}

	static class ViewHolder{
		TextView tvTitle;
		TextView tvSize;
		ImageView ivIcon;
		ProgressBar pbDownloading;
		TextView tvPercentage;
		CheckBox ckbSelect;
		Button bnSwitch;
		Button bnCancel;
	}
	
	public static String getErrorMsg(int errorCode){
		String retval;
		switch (errorCode) {
		case DownloadBaseJob.ErrorCode.ERROR_IO:
			retval = "IO异常";
			break;
		case DownloadBaseJob.ErrorCode.ERROR_NETWORK:
			retval = "网络异常";
			break;
		case DownloadBaseJob.ErrorCode.ERROR_SERVER:
			retval = "服务器异常";
			break;
		case DownloadBaseJob.ErrorCode.ERROR_OTHER_DOWNLOADING:
			retval = "下载过程中异常";
			break;
		default:
			retval = "未知异常";
			break;
		}
		return retval;
	}
	
	public static String getSwitchString(Context context, DownloadBaseJob<Entity> job){
		String retval = null;
		int state = job.getState();
		switch(state){
		case DownloadBaseJob.STATE_DOWNLOADING:
			retval = "暂停";
			break;
		case DownloadBaseJob.STATE_PAUSED:
			retval = "继续";
			break;
		case DownloadBaseJob.STATE_SUCCESS:
			boolean isAvailable = Utility.isPackageAvailable(context, job.getEntity().pkgName, job.getEntity().verCode);
			if (isAvailable) {
				retval = "打开";
			}else{
				retval = "安装";
			}
			break;
		case DownloadBaseJob.STATE_FAILED:
			retval = "重试";
			break;
		}
		return retval;
	}
		
	private OnClickListener onSwitchClickListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			int position = (Integer) v.getTag();
			int state = getItem(position).getState();
			switch (state) {
			case DownloadBaseJob.STATE_DOWNLOADING:
				getItem(position).onPause();
				break;
			case DownloadBaseJob.STATE_PAUSED:
				getItem(position).onResume();
				break;
			case DownloadBaseJob.STATE_SUCCESS:
				boolean isAvailable = Utility.isPackageAvailable(context, getItem(position).getEntity().pkgName, getItem(position).getEntity().verCode);
				if (isAvailable) {
					Utility.openApp(context, getItem(position).getEntity().pkgName);
				}else{
					Utility.installApk(context, getItem(position).getmHelper().getDownloadFile(context, getItem(position)));
				}
				break;
			case DownloadBaseJob.STATE_FAILED:
				getItem(position).onRetry();
				break;
			}
			notifyDataSetChanged();
		}
	};
	
	
	/**
	 * check local file and reset state
	 * @param job
	 */
	private void checkLocalFile(DownloadBaseJob<Entity> job){
		if (DownloadBaseJob.STATE_SUCCESS == job.getState()) {
			File file = job.getmHelper().getDownloadFile(context, job);
			if (file != null && !file.exists()) {
				job.setState(DownloadBaseJob.STATE_FAILED, false);
			}
		}
	}
	
	private OnClickListener onCalcelClickListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			int position = (Integer) v.getTag();
			DownloadJob job = (DownloadJob) getItem(position);
			job.onDelete();
			notifyDataSetChanged();
		}
	};
}
